//
//  BKTreeNode.cpp
//  NewBKTree
//
//  Created by Rune Juul Laugesen on 03/12/13.
//  Copyright (c) 2013 Rune Juul Laugesen. All rights reserved.
//

#include "BKTreeNode.h"

BKTreeNode::BKTreeNode(string name)
{
    _name = name;
}

BKTreeNode* BKTreeNode::childAtDistance(int pos)
{
    auto it = _children.find(pos);
    if (it == _children.end())
        return new BKTreeNode();
    else
        return (BKTreeNode* ) &it->second;
}

void BKTreeNode::addChild(int pos, BKTreeNode* child)
{
    _children.insert(pair<int, BKTreeNode>(pos, *child));
}

map<int, string> BKTreeNode::Search(string word, int maxdistance)
{
    int distance = LevenshteinDistance(_name, word);
    map<int, string> matches;
    map<int, string> childmatch;
    
    if (distance <= maxdistance)
        matches.insert(pair<int, string>(distance, _name));
    //matches.push_back(_name);
    
    if (_children.size() == 0)
        return matches;
    
    int i = max(1, distance - maxdistance);
    
    for (; i <= distance + maxdistance; i++)
    {
        map<int, BKTreeNode>::iterator it = _children.find(i);
        
        if (it == _children.end())
            continue;
        
        BKTreeNode child = (*it).second;
        childmatch = child.Search(word, maxdistance);
        matches.insert(childmatch.begin(), childmatch.end());
    }
    
    return matches;
}

string BKTreeNode::GetName()
{
    return _name;
}